package com.stony.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * Created by ShiHui on 2014/7/3.
 */
public class MyFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
    private Charset charset = UTF8;

    private SerializerFeature[] features = new SerializerFeature[0];

    public MyFastJsonHttpMessageConverter() {
        super();
    }

    public Charset getCharset() {
        return this.charset;
    }

    public void setCharset(Charset charset) {
        this.charset = charset;
    }

    public SerializerFeature[] getFeatures() {
        return features;
    }

    public void setFeatures(SerializerFeature... features) {
        this.features = features;
    }

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {

        OutputStream out = outputMessage.getBody();
        String text = JSON.toJSONString(obj, MySerializeConfig.getInstance(), features);
        byte[] bytes = text.getBytes(charset);
        out.write(bytes);
    }
}
